<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="10">
        <el-col :span="4">
          <el-select
            v-model="queryInfo.department_id"
            clearable
            placeholder="请选择学院"
            @clear="getClassList()"
          >
            <el-option
              v-for="item in collegesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="getClassList()"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加班级</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="classlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="班级序号" prop="id"></el-table-column>
        <el-table-column label="班级名称" prop="name"></el-table-column>
        <el-table-column label="学院" prop="school.name"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="排课"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showCoursePlan(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加班级的对话框 -->
    <el-dialog
      title="添加班级"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogVisible = false"
    >
      <el-form
        :model="addForm"
        :rules="FormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="班级名称" prop="name" label-width="85px">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="所属学院" prop="school_id" label-width="85px">
          <el-select v-model="addForm.school_id" placeholder="请选择学院">
            <el-option
              v-for="item in collegesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClass">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改班级的对话框 -->
    <el-dialog
      title="修改职位"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="FormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="班级名称" prop="name" label-width="85px">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="所属学院" prop="department" label-width="85px">
          <el-select v-model="editForm.school_id.name" placeholder="请选择部门">
            <el-option
              v-for="item in collegesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDepartment">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 为班级排课 -->
    <el-dialog
      title="班级排课"
      :visible.sync="coursePlanDialogVisible"
      width="50%"
      @close="closeCoursePlanDialog"
    >
      <el-form
        ref="courseFormRef"
        :model="courseFormData"
        :rules="courseFormRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="教学周期" prop="teaching_time">
          <el-select
            v-model="courseFormData.teaching_time"
            placeholder="请选择教学周期"
            @change="handleTimeChange"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in teachingcycleOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室号" prop="room_number">
          <el-input
            v-model="courseFormData.room_number"
            placeholder="请输入教室号"
            :maxlength="30"
            show-word-limit
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="带班讲师" prop="lecturer">
          <el-select
            v-model="courseFormData.lecturer"
            placeholder="请选择带班讲师"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in lecturerOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="辅导员" prop="counsellor">
          <el-select
            v-model="courseFormData.counsellor"
            placeholder="请选择辅导员"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in counsellorOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 课程版本 -->
        <el-form-item label="课程版本">
          <el-select
            v-model="versionData"
            placeholder="请选择课程版本"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in version"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程名称" prop="course">
          <el-select
            :disabled="!versionData.length"
            v-model="courseFormData.course"
            placeholder="请选择课程名称"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in courseOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="正课时间" prop="class_time">
          <el-checkbox-group v-model="courseFormData.class_time" size="medium">
            <el-checkbox
              v-for="(item, index) in classTimeOptions"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCoursePlanDialog">取 消</el-button>
        <el-button type="primary" @click="createCoursePlan()">{{
          currentId ? '修 改' : '确 定'
        }}</el-button>
      </span>
    </el-dialog>

    <!-- 为高职学院班级排课 -->
    <el-dialog
      title="班级排课"
      :visible.sync="gzCoursePlanDialogVisible"
      width="50%"
      @close="closeCoursePlanDialog"
    >
      <el-form
        ref="courseFormRef"
        :model="courseFormData"
        :rules="courseFormRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="教学周期" prop="teaching_time">
          <el-select
            v-model="courseFormData.teaching_time"
            placeholder="请选择教学周期"
            @change="handleTimeChange"
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in teachingcycleOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="请选择日期" prop="gzDateTime">
          <el-date-picker
            v-model="courseFormData.gzDateTime"
            type="datetime"
            placeholder="请选择日期"
          >
          </el-date-picker>
        </el-form-item> -->

        <el-form-item label="请选择日期" prop="gzDateTime">
          <el-select
            multiple
            v-model="courseFormData.gzDateTime"
            placeholder="请选择日期"
          >
            <el-option
              v-for="item in dateOptions"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="教室号" prop="room_number">
          <el-input
            v-model="courseFormData.room_number"
            placeholder="请输入教室号"
            :maxlength="30"
            show-word-limit
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>

        <el-form-item label="带班讲师" prop="lecturer">
          <el-select
            v-model="courseFormData.lecturer"
            placeholder="请选择带班讲师"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in lecturerOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="辅导员" prop="counsellor">
          <el-select
            v-model="courseFormData.counsellor"
            placeholder="请选择辅导员"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in counsellorOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 课程版本 -->
        <el-form-item label="课程版本">
          <el-select
            v-model="versionData"
            placeholder="请选择课程版本"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in version"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程名称" prop="course">
          <el-select
            :disabled="!versionData.length"
            v-model="courseFormData.course"
            placeholder="请选择课程名称"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in courseOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="正课时间" prop="class_time">
          <el-checkbox-group v-model="courseFormData.class_time" size="medium">
            <el-checkbox
              v-for="(item, index) in classTimeOptions"
              :key="index"
              :label="item.value"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCoursePlanDialog">取 消</el-button>
        <el-button type="primary" @click="createCoursePlan()">{{
          currentId ? '修 改' : '确 定'
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getClass,
  createClass,
  createCoursePlan,
  getCoursePlan,
  getIsGaoZhi,
  editRoleItem,
} from '../../api/class'
import { getAllDepartment } from '@/api/role'
import { getColleges } from '../../api/department'
import {
  getTeachingCycle,
  getTeachingCycleDateTime,
} from '../../api/teachingtime'
import { getTeacherByClassId } from '../../api/adminuser'
import { getCoursesByClassId } from '../../api/course'
import { removeClass } from '../../api/class'
import moment from 'moment'
export default {
  data() {
    return {
      gzCoursePlanDialogVisible: false,
      options: [],
      collegesOptions: [],
      queryInfo: {
        department_id: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      classlist: [],
      total: 0,

      // 添加表单数据
      addForm: {
        name: '',
        school_id: '',
      },
      // 添加、修改表单的验证规则对象
      FormRules: {
        name: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '班级名称的长度在2~10个字符之间',
            trigger: 'blur',
          },
        ],
        school_id: [{ required: true, message: '请选择学院', trigger: 'blur' }],
      },
      // 查询到的信息对象
      editForm: {
        id: 0,
        name: '',
        school_id: '',
      },
      coursePlanDialogVisible: false,
      currentId: 0,
      courseFormData: {
        cls: 0,
        teaching_time: undefined,
        room_number: undefined,
        lecturer: undefined,
        counsellor: undefined,
        course: undefined,
        class_time: [2, 3, 5, 6],
        gzDateTime: [],
      },
      courseFormRules: {
        teaching_time: [
          {
            required: true,
            message: '请选择教学周期',
            trigger: 'change',
          },
        ],
        gzDateTime: [
          {
            required: true,
            message: '请选择日期',
            trigger: 'change',
          },
        ],
        room_number: [
          {
            required: true,
            message: '请输入教室号',
            trigger: 'blur',
          },
        ],
        lecturer: [
          {
            required: true,
            message: '请选择带班讲师',
            trigger: 'change',
          },
        ],
        counsellor: [
          {
            required: true,
            message: '请选择辅导员',
            trigger: 'change',
          },
        ],
        course: [
          {
            required: true,
            message: '请选择课程名称',
            trigger: 'change',
          },
        ],
        class_time: [
          {
            required: true,
            type: 'array',
            message: '请选择正课课节',
            trigger: 'blur',
          },
        ],
      },
      teachingcycleOptions: [],
      lecturerOptions: [],
      counsellorOptions: [],
      courseOptions: [],
      classTimeOptions: [
        {
          label: '第一节课',
          value: 1,
        },
        {
          label: '第二节课',
          value: 2,
        },
        {
          label: '第三节课',
          value: 3,
        },
        {
          label: '第四节课',
          value: 4,
        },
        {
          label: '第五节课',
          value: 5,
        },
        {
          label: '第六节课',
          value: 6,
        },
        {
          label: '第七节课',
          value: 7,
        },
        {
          label: '第八节课',
          value: 8,
        },
      ],
      dateOptions:[],
      editDialogVisible: false,

      // 课程版本
      version: [],
      // 课程版本选择结果
      versionData: '',
      // 预留后面的版本做铺垫
      courseVersion: [],
    }
  },
  created() {
    this.getTeachingCycle()
    this.getClassList()
    this.getCollegesOptions()
  },
  methods: {
    //获取所有的学院信息
    async getCollegesOptions() {
      const result = await getColleges()
      this.collegesOptions = []
      if (result) {
        result.forEach((item) => {
          this.collegesOptions.push({
            value: item.id,
            label: item.name,
          })
        })
      }
    },
    //获取所有的教学周期
    async getTeachingCycle() {
      const result = await getTeachingCycle('activated')
      if (!result) return
      result.forEach((item) => {
        this.teachingcycleOptions.push({
          label: item.title,
          value: item.id,
        })
      })
    },
    //关闭排课对话框
    closeCoursePlanDialog() {
      this.$refs.courseFormRef.resetFields()
      this.coursePlanDialogVisible = false
    },

    async showCoursePlan(class_id) {
      var res = await getIsGaoZhi(class_id)
      if (res==1) {
        this.gzCoursePlanDialogVisible = true
      } else {
        this.coursePlanDialogVisible = true
      }
      this.currentId = 0
      this.courseFormData.cls = class_id

      const teachers = await getTeacherByClassId(class_id)
      this.counsellorOptions = []
      this.lecturerOptions = []
      if (teachers) {
        teachers.forEach((item) => {
          if (item.role__duty == 3) {
            this.counsellorOptions.push({
              label: item.name,
              value: item.id,
            })
          } else {
            this.lecturerOptions.push({
              label: item.name,
              value: item.id,
            })
          }
        })
      }
      const courses = await getCoursesByClassId(class_id)

      this.courseVersion = courses

      let version = []
      this.version = []
      this.versionData=""
      courses.forEach((item) => {
        version.push(item.version)
      })

      version = Array.from(new Set(version))
      version.forEach((item) => {
        this.version.push({
          label: item,
          value: item,
        })
      })

      this.courseOptions = []
    },
    createCoursePlan() {
      this.$refs['courseFormRef'].validate(async (valid) => {
        if (!valid) return
        // const res = await getTeachingCycleDateTime(
        //   this.courseFormData.teaching_time
        // )
        // var starttime = res.starttime
        // var endtime = res.endtime
        // starttime = moment(starttime).format('YYYY-MM-DD HH:mm:ss')
        // endtime = moment(endtime).format('YYYY-MM-DD HH:mm:ss')
        // this.courseFormData.gzDateTime = moment(
        //   this.courseFormData.gzDateTime
        // ).format('YYYY-MM-DD HH:mm:ss')
        // if (
        //   starttime <= this.courseFormData.gzDateTime &&
        //   this.courseFormData.gzDateTime <= endtime
        // ) {
        //   console.log('在时间段内')
        // } else {
        //   this.$message.error('请检查日期是否在教学周期之间！')
        //   return false
        // }

        if (this.gzCoursePlanDialogVisible == false) {
          if (this.courseFormData.class_time.length != 4) {
            this.$message.warning('正课必须选择四节课')
            return
          }
          this.courseFormData.gzDateTime = []
        }

        this.courseFormData.class_time.sort()
        this.courseFormData.class_time =
          this.courseFormData.class_time.join(',')
        console.log(this.courseFormData);
        const result = await createCoursePlan(this.courseFormData)
        if (result) {
          if (this.gzCoursePlanDialogVisible == true) {
            this.gzCoursePlanDialogVisible = false
          }
          this.closeCoursePlanDialog()
          this.$message.success('排课成功')
        }
      })
    },
    async handleTimeChange(val) {
      console.log(val)
      const res = await getTeachingCycleDateTime(val)
      console.log(res)
      
      let startDate = moment(res.starttime)
      let endDate = moment(res.endtime)
      this.dateOptions=[]
      if (endDate && startDate) {
        while (endDate >= startDate) {
          this.dateOptions.push(startDate.format('YYYY-MM-DD'))
          startDate.add(1, 'day')
        }
      }

      const coursePlan = await getCoursePlan(this.courseFormData.cls, val)
      console.log(coursePlan)
      if (coursePlan.id) {
        this.currentId = coursePlan.id
        delete coursePlan['id']
        coursePlan.class_time = coursePlan.class_time.split(',').map((item) => {
          return Number(item)
        })
        
        this.courseFormData = coursePlan
        console.log(JSON.parse(coursePlan.gzDateTime));

        this.courseFormData.gzDateTime = JSON.parse(coursePlan.gzDateTime)
      } else {
        this.$refs.courseFormRef.resetFields()
        this.courseFormData.teaching_time = val
      }
    },

    async getDepartmentList() {
      const departments = await getAllDepartment(1)
      if (departments) {
        departments.forEach((item) => {
          this.options.push({
            value: item.id,
            label: item.name,
          })
        })
      }
    },
    async getClassList() {
      const result = await getClass(this.queryInfo)
      this.classlist = result.data //列表中展示的数据内容
      this.total = result.count //数据总条数
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getClassList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getClassList()
    },
    //添加班级
    addClass() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(this.addForm)
        if (!valid) return
        // 可以发起添加用户的网络请求
        if (await createClass(this.addForm)) {
          this.addDialogClosed()
          this.getClassList()
          this.$message.success('添加班级成功！')
        }
      })
    },

    // 展示编辑的对话框
    async showEditDialog(id) {
      this.editDialogVisible = !this.editDialogVisible
      this.editForm.id = id.id
      this.editForm.name = id.name
      this.editForm.school_id = id.school
    },
    // 监听修改部门对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改部门信息并提交
    editDepartment() {
      // console.log(this.editForm)
      this.editForm.school_id = this.editForm.school_id.id
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const result = await editRoleItem(this.editForm.id, this.editForm)
        this.getClassList()
        if (result) {
          // 关闭对话框
          this.editDialogVisible = false
          // 提示修改成功
          this.$message.success('更新班级信息成功！')
        }
      })
    },
    // 根据Id删除对应的用户信息
    async removeRoleById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该职位, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      removeClass(id).then((value) => {
        this.$message.success('删除职位成功！')
        this.getClassList()
      })
    },
  },
  watch: {
    versionData() {
      this.courseOptions = []
      let a = this.courseVersion.filter((item) => {
        return item.version == this.versionData
      })

      a.forEach((item) => {
        this.courseOptions.push({
          label: item.name,
          value: item.id,
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
.el-date-editor,.el-select{
  width: 100%;
}
</style>
